﻿using EM.FrameWork;
using EM.FrameWork.Paging;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace EM.OA.Portal.Controllers
{
    public class DictionaryController : BaseAuthController
    {

        EM.OA.BLL.DictionaryBLL _dictionaryBll = new BLL.DictionaryBLL();

        public ActionResult Index()
        {
            //初始化字典表,字典表只能有一个根
            if (_dictionaryBll.GetList().Where(p => p.DictionaryParentID == new Guid() || !p.DictionaryParentID.HasValue).Count() < 1)
            {
                EMOA_Dictionary rootDictionary = new EMOA_Dictionary();
                rootDictionary.DictionaryID = Guid.NewGuid();
                rootDictionary.DictionaryCode = "0";
                rootDictionary.DictionaryParentID = Guid.Empty;
                rootDictionary.DictionaryName = "root";
                rootDictionary.IsSystem = true;
                rootDictionary.Status = (int)EM.OA.WebCommon.CommonEnum.Status.Normal;
                rootDictionary.CreateBy = CurrentUser.UserID;
                rootDictionary.CreateTime = DateTime.Now;
                _dictionaryBll.Add(rootDictionary);
            }
            return View();
        }

        public JsonResult GetList(string page, string rows)
        {
            List<EMOA_Dictionary> list = _dictionaryBll.GetList();
            List<object> nodelist = new List<object>();
            list.ForEach(p =>
            {
                if (!p.DictionaryParentID.HasValue || p.DictionaryParentID == new Guid())
                {
                    nodelist.Add(new { DictionaryID = p.DictionaryID, DictionaryCode = p.DictionaryCode, DictionaryName = p.DictionaryName, IsSystem = p.IsSystem, Remark = p.Remark });
                }
                else
                {
                    nodelist.Add(new { DictionaryID = p.DictionaryID, DictionaryCode = p.DictionaryCode, DictionaryName = p.DictionaryName, IsSystem = p.IsSystem, Remark = p.Remark, _parentId = p.DictionaryParentID });
                }
            });

            return ToJson(nodelist, list.Count);
        }

        public ActionResult GetTreeList()
        {
            List<EMOA_Dictionary> list = _dictionaryBll.GetList();
            List<TreeNode> nodeList = new List<TreeNode>();
            list.ForEach(p =>
            {
                nodeList.Add(new TreeNode(p.DictionaryID, p.DictionaryParentID.Value, p.DictionaryName));
            });

            TreeNodeHelper helper = new TreeNodeHelper();
            TreeNode treeNode = new TreeNode();
            treeNode = helper.GenerateTreeRoot(nodeList);

            string result = treeNode.ToJsonTreeString();
            return Content(result);
        }

        public ActionResult GetEntity(Guid id)
        {
            var data = _dictionaryBll.GetEntity(id); ;
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Create(DictionaryModels model)
        {
            try
            {
                EMOA_Dictionary ep = model.ToEntity<EMOA_Dictionary>();
                ep.DictionaryID = Guid.NewGuid();
                ep.CreateBy = CurrentUser.UserID;
                ep.CreateTime = DateTime.Now;
                if (_dictionaryBll.Add(ep))
                {
                    return Content("OK");
                }
                else
                {
                    return Content("失败");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        [HttpPost]
        public ActionResult Edit(DictionaryModels model)
        {
            try
            {
                EMOA_Dictionary entity = _dictionaryBll.GetEntity(model.DictionaryID);
                entity = model.ToEntity<EMOA_Dictionary>(entity);
                entity.UpdateBy = CurrentUser.UserID;
                entity.UpdateTime = DateTime.Now;
                if (_dictionaryBll.Update(entity))
                    return Content("OK");
                else
                    return Content("失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Delete(Guid id)
        {
            try
            {
                if (_dictionaryBll.GetList(p=>p.DictionaryParentID==id).Count() > 0)
                {
                    return Content("请先删除子集！");
                }
                else
                {
                    if (_dictionaryBll.Delete(id))
                        return Content("OK");
                    else
                        return Content("失败");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 获取指定的编码类型
        /// 获取某节点子节点列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDicByCode(string code)
        {
            List<EMOA_Dictionary> list = _dictionaryBll.GetDicList(code);

            return Json(list);
        }

        /// <summary>
        /// Add by Sun Gongfa 2013-04-14
        /// 获取某节点以及其字节点
        /// _kind：节点Code
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDictionaryListByCode()
        {
            string _kind = Request.QueryString["kind"].ToString();
            List<EMOA_Dictionary> list = _dictionaryBll.GetDicList(_kind).Union(_dictionaryBll.GetList(p => p.DictionaryCode == _kind)).ToList();
            List<object> nodelist = new List<object>();
            list.ForEach(p =>
            {
                nodelist.Add(new DictionaryModels().ToModel<EMOA_Dictionary>(p));
            });

            Dictionary<string, object> json = new Dictionary<string, object>();

            json.Add("total", list.Count);

            json.Add("rows", nodelist);
            var jsonResult = new { total = list.Count(), rows = nodelist };

            return Json(json);
        }

        public ActionResult GetDictionaryListByCode2()
        {
            string _kind = Request.QueryString["kind"].ToString();
            string _name = HttpUtility.UrlDecode(Request["name"], Encoding.GetEncoding("gb2312"));

            List<EMOA_Dictionary> list = _dictionaryBll.GetDicList(_kind);

            string resultStr = "";
            resultStr += "[";
            resultStr += "{";
            resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"selected\": \"true  \"", "", "请选择" + _name);
            resultStr += "},";
            foreach (EMOA_Dictionary item in list)
            {
                resultStr += "{";
                resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\"", item.DictionaryID.ToString(), item.DictionaryName);
                resultStr += "},";
            }
            resultStr = resultStr.Substring(0, resultStr.Length - 1);
            resultStr += "]";
            return Content(resultStr);
        }

    }
}
